package monitor

import (
	"fmt"
	"os"
	"time"

	"github.com/gookit/slog"
	"github.com/gookit/slog/handler"
	"github.com/shirou/gopsutil/mem"
	"github.com/shirou/gopsutil/process"
)

type Resource struct {
	stopChan chan struct{}
}

func (s *Resource) ResourceMonitor() {
	// 创建专用的性能日志记录器
	perfLogger := slog.NewWithHandlers(handler.MustFileHandler("logs/perf_resource.log", handler.WithLogLevels(slog.AllLevels)))

	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()

	// osType := runtime.GOOS
	// 获取当前进程
	p, err := process.NewProcess(int32(os.Getpid()))
	if err != nil {
		perfLogger.Error(fmt.Sprintf("无法获取进程信息: %v", err))
		return
	}

	for {
		select {
		case <-ticker.C:
			// 获取系统总内存
			memInfo, err := mem.VirtualMemory()
			if err != nil {
				perfLogger.Error(fmt.Sprintf("获取内存信息失败: %v", err))
				continue
			}

			// 获取当前进程CPU使用率
			cpuPercent, err := p.CPUPercent()
			if err != nil {
				perfLogger.Error(fmt.Sprintf("获取CPU使用率失败: %v", err))
				continue
			}

			// 获取当前进程内存信息
			memInfoProc, err := p.MemoryInfo()
			if err != nil {
				perfLogger.Error(fmt.Sprintf("获取进程内存信息失败: %v", err))
				continue
			}

			// 计算内存使用百分比
			memPercent := float64(memInfoProc.RSS) / float64(memInfo.Total) * 100
			perfLogger.Info(fmt.Sprintf("当前程序 CPU 利用率: %.2f%%，内存占用: %.2f%% (%.2f MB/%.2f GB)",
				cpuPercent, memPercent,
				float64(memInfoProc.RSS)/1024/1024,
				float64(memInfo.Total)/1024/1024/1024))

		case <-s.stopChan:
			return
		}
	}
}
